/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.race.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import javax.xml.bind.SchemaOutputResolver;

import com.google.common.collect.Lists;
import com.lczyfz.istep.common.utils.excel.ExportExcel;
import com.lczyfz.istep.common.utils.excel.ImportExcel;
import com.lczyfz.istep.modules.race.entity.RaceTeam;
import com.lczyfz.istep.modules.race.service.RaceTeamService;
import com.lczyfz.istep.modules.sys.service.SystemService;
import com.lczyfz.istep.modules.sys.utils.UserUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.modules.race.entity.RaceUser;
import com.lczyfz.istep.modules.race.service.RaceUserService;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 竞赛账号管理Controller
 * @author CY
 * @version 2017-04-17
 */
@Controller
@RequestMapping(value = "${adminPath}/race/raceUser")
public class RaceUserController extends BaseController {
	@Autowired
	private RaceUserService raceUserService;
	@Autowired
	private RaceTeamService raceTeamService;

	@ModelAttribute
	public RaceUser get(@RequestParam(required=false) String id) {
		RaceUser entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = raceUserService.get(id);
		}
		if (entity == null){
			entity = new RaceUser();
		}
		return entity;
	}
	
	@RequiresPermissions("race:raceUser:view")
	@RequestMapping(value = {"list", ""})
	public String list(RaceUser raceUser, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<RaceUser> page = raceUserService.findPage(new Page<RaceUser>(request, response), raceUser);
		model.addAttribute("page", page);


		return "modules/race/raceUserList";
	}

	@ResponseBody
	@RequestMapping(value = "listDetails")
	public RaceUser listDetails(String id){
		return raceUserService.findId(id);
	}

	@ResponseBody
	@RequestMapping(value = "lists")
	public List<RaceUser> lists(){
		return raceTeamService.findAllListUser();
	}


	@RequiresPermissions("race:raceUser:view")
	@RequestMapping(value = "form")
	public String form(RaceUser raceUser, Model model) {
		model.addAttribute("raceUser", raceUser);
		List<RaceTeam> raceTeams = raceUserService.findAllClassList();
		model.addAttribute("raceTeams", raceTeams);
		return "modules/race/raceUserForm";
	}


	@RequiresPermissions("race:raceUser:edit")
	@RequestMapping(value = "save")
	public String save(RaceUser raceUser, Model model, RedirectAttributes redirectAttributes) {


		if (!beanValidator(model, raceUser)){
			return form(raceUser, model);
		}


		if (raceUser.getId()==null||raceUser.getId().equals("")){
			raceUser.setPassword(SystemService.entryptPassword(raceUser.getPassword()));
			raceUserService.save(raceUser);
			RaceUser raceUser1 = new RaceUser();
			raceUser1.setUserId(raceUser.getId());
			raceUser1.setRoleId("4");
			raceUserService.inpuUserRole(raceUser1);

			if (raceUser.getTeamId() != null){
				RaceTeam raceTeam = new RaceTeam();
				raceTeam.setUserId(raceUser.getId());
				List<RaceTeam> raceTeams = raceUserService.findAllClassList();
				for (RaceTeam raceTeam1 : raceTeams){
					if (raceTeam1.getTeamName().equals(raceUser.getTeamId())){
						raceTeam.setTeamId(raceTeam1.getId());
					}
				}
				raceTeamService.raceUserTeam(raceTeam);
			}
		}else{


			System.out.println("----" + raceUser.getId() + "====" + raceUser.getPassword());

			if (raceUser.getPassword().equals(",.,")){
				RaceUser raceUser1 = raceUserService.get(raceUser.getId());
				raceUser.setPassword(raceUser1.getPassword());
			}else {
				raceUser.setPassword(SystemService.entryptPassword(raceUser.getPassword()));
			}


			if (raceUserService.get(raceUser) == null) {

				if (raceUserService.findByName(raceUser.getLoginName()) != null) {
					addMessage(redirectAttributes, "保存竞赛账号失败");
					return "redirect:" + Global.getAdminPath() + "/race/raceUser/?repage";
				} else {
					raceUserService.save(raceUser);
				}

			} else {
				List<RaceUser> raceUserList = raceUserService.findList(new RaceUser());
				int count = 0;
				for (RaceUser raceUser1 : raceUserList) {
					if (!raceUser1.getId().equals(raceUser.getId())) {
						if (raceUser1.getLoginName().equals(raceUser.getLoginName())) {
							count++;
						}
					}
				}
				if (count == 0) {
					addMessage(redirectAttributes, "编辑竞赛账号成功");
					raceUserService.save(raceUser);
				} else {
					addMessage(redirectAttributes, "重复的竞赛账号，编辑竞赛账号失败");
					return "redirect:" + Global.getAdminPath() + "/race/raceUser/?repage";
				}
			}

            RaceTeam raceTeam = new RaceTeam();
			raceTeam.setUserId(raceUser.getId());
			List<RaceTeam> raceTeams = raceUserService.findAllClassList();
			for (RaceTeam raceTeam1 : raceTeams){
				if (raceTeam1.getTeamName().equals(raceUser.getTeamId())){
					raceTeam.setTeamId(raceTeam1.getId());
				}
			}
              raceTeamService.updateRaceUserId(raceTeam);
		}


		if (raceUser.getLoginName().equals(UserUtils.getUser().getLoginName())) {
			UserUtils.clearCache();
			//UserUtils.getCacheMap().clear();
		}


		return "redirect:"+Global.getAdminPath()+"/race/raceUser/?repage";
	}
	
	@RequiresPermissions("race:raceUser:edit")
	@RequestMapping(value = "delete")
	public String delete(RaceUser raceUser, RedirectAttributes redirectAttributes) {

		raceUserService.deleteUserRole(raceUser);
		raceTeamService.deleteRaceUserId(raceUser.getId());


	raceUserService.delete(raceUser);
		addMessage(redirectAttributes, "删除竞赛账号管理成功");
		return "redirect:"+Global.getAdminPath()+"/race/raceUser/?repage";
	}


	/**
	 * 下载导入竞赛账号数据模板
	 *
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "竞赛账号导入模板.xlsx";
			List<RaceUser> list = Lists.newArrayList();
			RaceUser raceUser = raceUserService.get(UserUtils.getUser().getId());
			raceUser.setTeamId("必填");
			raceUser.setLoginName("必填");
			raceUser.setPassword("必填");
			raceUser.setName("必填");
			raceUser.setMobile("可填");
			raceUser.setEmail("可填");
			raceUser.setOrganization("可填");
			list.add(raceUser);
			logger.debug("=Evan==竞赛账号导入模板==" +list);
			new ExportExcel("竞赛账号", RaceUser.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/race/raceUser/?repage";
	}


	/**
	 * 导入学生账号
	 *
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		List<RaceTeam> raceTeams = raceUserService.findAllClassList();
		List<RaceUser> raceUsers2 = raceTeamService.findAllListUser();
		try {
			int successNum = 0;
			int failureNum = 0;
			int teamNum = 0;
			int userNum = 0;
			//StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<RaceUser> list = ei.getDataList(RaceUser.class);
			//logger.debug("=Evan==importFile==" + list);
			int mun = 0;
			for (RaceUser raceUser : list) {
				mun++;

				System.out.println("----" + raceUser.getTeamId());

				if (mun >= 2 && !raceUser.getTeamId().equals("") && raceUser.getTeamId() != null) {
					for (RaceTeam raceTeam1 : raceTeams) {
						if (raceUser.getTeamId().equals(raceTeam1.getTeamName()) || raceUser.getTeamId() == null || raceUser.getTeamId() == "") {
							teamNum++;
						}
					}
					for (RaceUser raceUser1 : raceUsers2) {
						if (raceUser.getLoginName().equals(raceUser1.getLoginName())) {
							userNum++;
						}
					}
					if ((raceUser.getPassword() == null || raceUser.getPassword() == "") && teamNum != 0 && userNum == 0 && raceUser.getLoginName() != null && !raceUser.getLoginName().equals("") && raceUser.getName() != null && !raceUser.getName().equals("")) {

						raceUser.setPassword(SystemService.entryptPassword("123456"));
						raceUserService.save(raceUser);
						RaceUser raceUser1 = new RaceUser();
						raceUser1.setUserId(raceUser.getId());
						raceUser1.setRoleId("4");
						raceUserService.inpuUserRole(raceUser1);


						if (raceUser.getTeamId() != null) {
							RaceTeam raceTeam = new RaceTeam();
							raceTeam.setUserId(raceUser.getId());
							List<RaceTeam> raceTeams1 = raceUserService.findAllClassList();
							for (RaceTeam raceTeam1 : raceTeams1) {
								if (raceTeam1.getTeamName().equals(raceUser.getTeamId())) {
									raceTeam.setTeamId(raceTeam1.getId());
								}
							}
							raceTeamService.raceUserTeam(raceTeam);
						}


						successNum++;
					} else if ((raceUser.getPassword() != null || raceUser.getPassword() == "") && teamNum != 0 && userNum == 0 && raceUser.getLoginName() != null && !raceUser.getLoginName().equals("") && raceUser.getName() != null && !raceUser.getName().equals("")) {
						raceUser.setPassword(SystemService.entryptPassword(raceUser.getPassword()));
						raceUserService.save(raceUser);
						RaceUser raceUser1 = new RaceUser();
						raceUser1.setUserId(raceUser.getId());
						raceUser1.setRoleId("4");
						raceUserService.inpuUserRole(raceUser1);


						if (raceUser.getTeamId() != null) {
							RaceTeam raceTeam = new RaceTeam();
							raceTeam.setUserId(raceUser.getId());
							List<RaceTeam> raceTeams1 = raceUserService.findAllClassList();
							for (RaceTeam raceTeam1 : raceTeams1) {
								if (raceTeam1.getTeamName().equals(raceUser.getTeamId())) {
									raceTeam.setTeamId(raceTeam1.getId());
								}
							}
							raceTeamService.raceUserTeam(raceTeam);
						}


						successNum++;
					} else {
						failureNum++;
					}
					userNum = 0;
					teamNum = 0;
				}else {
					if (mun >= 2) {
						failureNum++;
					}
				}
			}
			addMessage(redirectAttributes, "已成功导入： " + successNum + "条，     失败：" + failureNum + "条");

		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息：" + e.getMessage());
		}
		 return "redirect:"+Global.getAdminPath()+"/race/raceUser/?repage";
	}

    //导出
	@RequestMapping(value = "export")
	public String export(RedirectAttributes redirectAttributes, HttpServletResponse response) {
//		// 第一步，创建一个webbook，对应一个Excel文件
//		HSSFWorkbook wb = new HSSFWorkbook();
//		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
//		HSSFSheet sheet = wb.createSheet("竞赛账号");
//		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
//		HSSFRow row = sheet.createRow((int) 0);
//		// 第四步，创建单元格，并设置值表头 设置表头居中
//		HSSFCellStyle style = wb.createCellStyle();
//		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
//
//		HSSFCell cell = row.createCell((short) 0);
//		cell.setCellValue("登陆名");
//		cell.setCellStyle(style);
//		cell = row.createCell((short) 1);
//		cell.setCellValue("密码");
//		cell.setCellStyle(style);
//		cell = row.createCell((short) 2);
//		cell.setCellValue("姓名");
//		cell.setCellStyle(style);
//		cell = row.createCell((short) 3);
//		cell.setCellValue("团队");
//		cell.setCellStyle(style);
//		cell = row.createCell((short) 4);
//		cell.setCellValue("手机");
//		cell.setCellStyle(style);
//		cell = row.createCell((short) 5);
//		cell.setCellValue("邮箱");
//		cell.setCellStyle(style);
//		cell = row.createCell((short) 6);
//		cell.setCellValue("组织");
//		cell.setCellStyle(style);
//		// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
//		List list = raceTeamService.findAllListUser();
//		for (int i = 0; i < list.size(); i++)
//		{
//			row = sheet.createRow((int) i + 1);
//			RaceUser ru = (RaceUser) list.get(i);
//			// 第四步，创建单元格，并设置值
//			row.createCell((short) 0).setCellValue(ru.getLoginName());
//			row.createCell((short) 1).setCellValue(ru.getPassword());
//			row.createCell((short) 2).setCellValue(ru.getName());
//			row.createCell((short) 3).setCellValue(ru.getTeamId());
//			row.createCell((short) 4).setCellValue(ru.getMobile());
//			row.createCell((short) 5).setCellValue(ru.getEmail());
//			row.createCell((short) 6).setCellValue(ru.getOrganization());
//		}
//		// 第六步，将文件存到指定位置
//		try
//		{
//			File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
//
//
//			 String aa  = getClass().getResource("/").getFile().toString();
//
//			System.out.println("---------------" + aa);
//
//			String desktopPath = desktopDir.getAbsolutePath();
////			System.out.println("----" + desktopPath);
//
//			SimpleDateFormat df = new SimpleDateFormat("yy");//设置日期格式
//			    SimpleDateFormat df1 = new SimpleDateFormat("HH");
//			    SimpleDateFormat df2 = new SimpleDateFormat("mm");
//			    SimpleDateFormat df3 = new SimpleDateFormat("ss");
//			FileOutputStream fout = new FileOutputStream(desktopPath+"/RU"+df.format(new Date())+df1.format(new Date())+df2.format(new Date())+df3.format(new Date())+".xls");
//
////			System.out.println("--++--" + desktopPath+"/RU"+df.format(new Date())+df1.format(new Date())+df2.format(new Date())+df3.format(new Date())+".xls");
//			wb.write(fout);
//			fout.close();
//			addMessage(redirectAttributes, "已成功导出到桌面");
//		}
//		catch (Exception e)
//		{
//			addMessage(redirectAttributes, "导出失败");
//			e.printStackTrace();
//		}
//


		try {
			String fileName = "竞赛账号导出数据.xlsx";
			List<RaceUser> list = Lists.newArrayList();
			List<RaceUser> raceUsers = raceTeamService.findAllListUser();
			for (int i = 0; i < raceUsers.size(); i++)
		{
			RaceUser raceUser = raceUserService.get(UserUtils.getUser().getId());

			raceUser.setTeamId(raceUsers.get(i).getTeamId());
			raceUser.setLoginName(raceUsers.get(i).getLoginName());
			raceUser.setPassword(raceUsers.get(i).getPassword());
			raceUser.setName(raceUsers.get(i).getName());
			raceUser.setMobile(raceUsers.get(i).getMobile());
			raceUser.setEmail(raceUsers.get(i).getEmail());
			raceUser.setOrganization(raceUsers.get(i).getOrganization());
			list.add(raceUser);
		}
			logger.debug("=Evan==竞赛账号导出==" + list);
			new ExportExcel("竞赛账号", RaceUser.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出失败！失败信息：" + e.getMessage());
		}


		return "redirect:"+Global.getAdminPath()+"/race/raceUser/?repage";
	}

















}